package output;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import forum.ForumItem;
import forum.ForumPost;
import forum.ForumSentence;
import forum.ForumTag;

public class SpreadSheetOutput implements Output {

	private BufferedWriter out;
	private String dl;

	public SpreadSheetOutput(File output, String delimiter) throws IOException {
		out = new BufferedWriter(new FileWriter(output));
		this.dl = delimiter;
		out.append("postId" + dl + "source" + dl + "poster" + dl + "title" + dl
				+ "date" + dl + "link" + dl);
		out.append("sentId" + dl + "emotion" + dl + "text" + dl);
		out.append("itemId" + dl + "itemName" + dl);
		out.append("topicId" + dl + "topicName" + dl);
		out.append("categoryName" + dl);
		out.append("tagId" + dl + "tagName" + dl);
		out.append("\r\n");
	}

	@Override
	public void outputThread(List<ForumPost> f) throws Exception {
		for (ForumPost fp : f) {
			for (ForumSentence fs : fp.getSentences()) {
				for (ForumItem fi : fs.getItems()) {
					for (ForumTag ft : fp.getForumTags()) {
						// Post
						out.append(fp.getPostId() + dl + fp.getSource() + dl
								+ fp.getPoster().replaceAll(dl, " ") + dl
								+ fp.getTitle().replaceAll(dl, " ") + dl
								+ fp.getPostDate() + dl
								+ fp.getHyperlink().replaceAll(dl, " ") + dl);
						// Sentence
						out.append(fs.getSentId()
								+ dl
								+ fs.getEmotion()
								+ dl
								+ fs.getText().replaceAll(dl, " ")
										.replace('"', '\'') + dl);
						// Item
						out.append(fi.getItemId() + dl + fi.getItemName() + dl);

						// Topic
						out.append(fi.getTopic().getTopicId() + dl
								+ fi.getTopic().getTopicName() + dl);
						// Category
						out.append(fp.getForumCategory() + dl);

						// Tag
						out.append(ft.getTagId() + dl + ft.getTagName() + dl);

						// End of line
						out.append("\r\n");
					}
				}
			}
		}
	}

	@Override
	public void close() throws IOException {
		out.flush();
		out.close();
	}
}
